package org.myspringmvc.web.servlet;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;

import java.util.List;

/**
 * @author 莫磊
 * @date 2025/8/12
 * @description 处理器执行链，包含处理器方法和拦截器List
 */
@Data
public class HandlerExecutionChain {
    /**
     * 处理器方法HandlerMethod
     */
    private Object handler;

    private List<HandlerInterceptor> interceptors;

    private int interceptorIndex = -1;

    public HandlerExecutionChain() {

    }

    public HandlerExecutionChain(List<HandlerInterceptor> interceptors, Object handler) {
        this.interceptors = interceptors;
        this.handler = handler;
    }

    public boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {

        for (int i = 0; i < this.interceptors.size(); i++) {
            if (!interceptors.get(i).preHandle(request, response, this.handler)) {
                // 执行afterCompletion方法
                afterCompletion(request, response);
                return false;
            }
            interceptorIndex = i;
        }
        return true;
    }

    public void applyPostHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        for (int i = this.interceptorIndex; i >= 0; i--) {
            interceptors.get(i).postHandle(request, response, this.handler);
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response) throws Exception {
        for (int i = this.interceptorIndex; i >= 0; i--) {
            interceptors.get(i).afterCompletion(request, response, this.handler);
        }
    }
}
